<!DOCTYPE html>
<html>

<head>
    <title>custom-skybox</title>
    <script type="text/javascript" src="https://unpkg.com/dat.gui@0.7.6/build/dat.gui.min.js"></script>
    <link type="text/css" rel="stylesheet" href="https://unpkg.com/maptalks/dist/maptalks.css">
    <script type="text/javascript" src="https://unpkg.com/maptalks/dist/maptalks.js"></script>
    <script type="text/javascript" src="https://unpkg.com/three@0.138.0/build/three.min.js"></script>
    <script type="text/javascript"
        src="https://unpkg.com/three@0.138.0/examples/js/libs/stats.min.js"></script>
    <script type="text/javascript" src="https://unpkg.com/maptalks.three@latest/dist/maptalks.three.js"></script>
    <script type="text/javascript" src="./buildings.js"></script>
    <style>
        html,
        body {
            margin: 0px;
            height: 100%;
            width: 100%;
        }

        #map {
            width: 100%;
            height: 100%;
            background-color: #000;
        }
    </style>
</head>

<body>
    <div id="map"></div>
    <script>

        const baseLayer = new maptalks.TileLayer("tile", {
            urlTemplate: "https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png",
            subdomains: ["a", "b", "c", "d"],
            attribution:
                '&copy; <a href="http://osm.org">OpenStreetMap</a> contributors, &copy; <a href="https://carto.com/">CARTO</a>'
        });

        var map = new maptalks.Map("map", {
            center: [13.414049129456203, 52.53160987202452],
            zoom: 17,
            pitch: 80,
            bearing: 180,

            centerCross: true,
            doubleClickZoom: false
            // baseLayer
        });
        map.addLayer(baseLayer);

        // features to draw
        var features = [];

        buildings.forEach(function (b) {
            features = features.concat(b.features);
        });

        // the ThreeLayer to draw buildings
        var threeLayer = new maptalks.ThreeLayer("t", {
            forceRenderOnMoving: true,
            forceRenderOnRotating: true
            // animation: true
        });

        var meshs = [];
        var material = getBuildingsMaterial();
        material.vertexColors = THREE.VertexColors;
        const topColor = new THREE.Color("white");

        threeLayer.prepareToDraw = function (gl, scene, camera) {
            var light = new THREE.DirectionalLight(0xffffff);
            light.position.set(0, -10, 10).normalize();
            scene.add(light);
            camera.add(new THREE.PointLight("#fff", 2));

            var heightPerLevel = 10;
            var polygons = features.map((f) => {
                const polygon = maptalks.GeoJSON.toGeometry(f);
                var levels = f.properties.levels || 1;
                polygon.setProperties({
                    height: heightPerLevel * levels
                });
                return polygon;
            });

            const mesh = threeLayer.toExtrudePolygons(
                polygons,
                { interactive: false },
                material
            );

            const bufferGeometry = mesh.getObject3d().geometry;
            const geometry = new THREE.Geometry().fromBufferGeometry(bufferGeometry);

            const { vertices, faces, faceVertexUvs } = geometry;
            for (let i = 0, len = faces.length; i < len; i++) {
                const { a, b, c } = faces[i];
                const p1 = vertices[a],
                    p2 = vertices[b],
                    p3 = vertices[c];
                //top face
                if (p1.z > 0 && p2.z > 0 && p3.z > 0) {
                    const vertexColors = faces[i].vertexColors;
                    for (let j = 0, len1 = vertexColors.length; j < len1; j++) {
                        vertexColors[j].r = topColor.r;
                        vertexColors[j].g = topColor.g;
                        vertexColors[j].b = topColor.b;
                    }
                    const uvs = faceVertexUvs[0][i];
                    for (let j = 0, len1 = uvs.length; j < len1; j++) {
                        uvs[j].x = 0;
                        uvs[j].y = 0;
                    }
                }
            }
            mesh.getObject3d().geometry = new THREE.BufferGeometry().fromGeometry(
                geometry
            );
            bufferGeometry.dispose();
            geometry.dispose();
            meshs.push(mesh);
            threeLayer.addMesh(meshs);
            initGui();
            animation();
        };
        threeLayer.addTo(map);

        var threeLayerSky = new maptalks.ThreeLayer(maptalks.Util.GUID(), {
            forceRenderOnMoving: true,
            forceRenderOnRotating: true,
            animation: true
        });
        threeLayerSky.prepareToDraw = function (gl, scene, camera) {
            this.setZIndex(-1000);
            var light = new THREE.DirectionalLight(0xffffff);
            light.position.set(0, -10, 10).normalize();
            scene.add(light);
            camera.add(new THREE.PointLight("#fff", 2));

            var r = "http://stemkoski.github.io/Three.js/images/dawnmountain-";
            var urls = [
                r + "xpos.png",
                r + "xneg.png",
                r + "ypos.png",
                r + "yneg.png",
                r + "zpos.png",
                r + "zneg.png"
            ];

            var textureCube = new THREE.CubeTextureLoader().load(urls);

            scene.background = textureCube;
            scene.rotation.x = -Math.PI / 2;
        };
        threeLayerSky.addTo(map);

        function getBuildingsMaterial(color = "red") {
            const texture = new THREE.TextureLoader().load('./data/building.png');
            texture.needsUpdate = true; //使用贴图时进行更新
            texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
            // texture.repeat.set(0.002, 0.002);
            texture.repeat.set(1, 4);
            const material = new THREE.MeshPhongMaterial({
                map: texture,
                transparent: true,
                color: "#fff"
            });
            return material;
        }

        function animation() {
            // layer animation support Skipping frames
            threeLayer._needsUpdate = !threeLayer._needsUpdate;
            if (threeLayer._needsUpdate) {
                threeLayer.redraw();
            }
            requestAnimationFrame(animation);
        }

        function initGui() {
            var params = {
                add: true,
                color: material.color.getStyle(),
                show: true,
                opacity: 1,
                altitude: 0,
                animateShow: animateShow
            };
            var gui = new dat.GUI();
            gui.add(params, "add").onChange(function () {
                if (params.add) {
                    threeLayer.addMesh(meshs);
                } else {
                    threeLayer.removeMesh(meshs);
                }
            });
            gui
                .addColor(params, "color")
                .name("building color")
                .onChange(function () {
                    material.color.set(params.color);
                    meshs.forEach(function (mesh) {
                        mesh.setSymbol(material);
                    });
                });
            gui.add(params, "opacity", 0, 1).onChange(function () {
                material.opacity = params.opacity;
                meshs.forEach(function (mesh) {
                    mesh.setSymbol(material);
                });
            });
            gui.add(params, "altitude", 0, 300).onChange(function () {
                meshs.forEach(function (mesh) {
                    mesh.setAltitude(params.altitude);
                });
            });
            gui.add(params, "animateShow");
        }

        function animateShow() {
            meshs.forEach(function (mesh) {
                mesh.animateShow({
                    duration: 3000
                });
            });
        }



    </script>
</body>

</html>